package org.study.tomcat_study.demo.simple;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import com.google.common.base.Charsets;

import lombok.Getter;
import lombok.Setter;

public class Response {

	private static final int BUFFER_SIZE = 1 << 10;
	@Getter
	@Setter
	Request request;
	@Getter
	@Setter
	OutputStream output;
	@Getter
	@Setter
	private Charset charset=Charset.forName("UTF-8");

	public Response() {
		super();
	}

	public void sendStaticResource() throws IOException {
		byte[] bytes = new byte[BUFFER_SIZE];

		FileInputStream fis = null;
		try {
			String uri = request.getUri();
			File file = new File(HttpServer.WEB_ROOT,uri);
			if (file.exists()) {
				if(file.isDirectory()) {
					error(output, "<html><h1>request directory is not allowed</h1></html>");
					return;
				}
				System.out.println("请求文件路径：" + file.getAbsolutePath());
				fis = new FileInputStream(file);
				int ch;
				out(output,"",file.length());
				while ((ch = fis.read(bytes, 0, BUFFER_SIZE)) != -1) {
					output.write(bytes, 0, ch);
				}
			} else {
				// 404 not found
				String errorMessage = "HTTP/1.1 404 NOT FOUND\r\n Content-Type: text/html\r\n Content-Length: 23\r\n\r\n <h1>File Not Found</h1>";
				output.write(errorMessage.getBytes(Charsets.UTF_8));
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (fis != null) {
				fis.close();
			}
		}
	}

	public void error(OutputStream output,String str) {
		if(str==null)return;
		String title=String.format("HTTP/1.1 500 SERVER ERROR\r\n Content-Type: text/html\r\n Content-Length: %d\r\n\r\n",str.length());
		try {
			output.write((title+str).getBytes(charset));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void out(OutputStream output,String str,long length) {
		String title = String.format("HTTP/1.1 200 OK\r\n Content-Type: text/html\r\n Content-Length: %d\r\n\r\n",length);
		try {
			output.write((title+str).getBytes(charset));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Response(OutputStream output) {
		super();
		this.output = output;
	}

	public static void main(String[] args) throws IOException {
		File file = new File(HttpServer.WEB_ROOT, "/index.html");
		FileInputStream fis = new FileInputStream(file);
		byte[] arr = new byte[2 << 10];
		fis.read(arr);
		System.out.println(new String(arr, Charsets.UTF_8));
	}

}
